package com.zgw.his.emr.resource;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.Properties;

import org.eclipse.core.runtime.Platform;

/**
 * 模板管理站点
 * 
 * @author Z.G.W
 * */
public final class TemplateSite {

	public static final String DEFAULT_ROOT_PAT = Platform.getInstallLocation()
			.getURL().getPath()
			+ "template_lib/";// 默认模板存储目录
	private static final String CONFIG_PATH = DEFAULT_ROOT_PAT
			+ "config.properties";// 模板配置路径

	private static Properties configFile;

	// 加载默认的模板, 即模板存储根目录下所有模板文件
	public static void loadDefault() {
		try {
			configFile = new Properties();
			File f = new File(DEFAULT_ROOT_PAT);
			File[] children = f.listFiles(new FileFilter() {
				public boolean accept(File pathname) {
					return pathname.isFile()
							&& pathname.getName().endsWith(".xwt");
				}
			});
			if (children != null) {
				for (File c : children) {
					configFile.setProperty(c.getName(), c.getPath());
				}
				OutputStream out = new FileOutputStream(CONFIG_PATH);
				try {
					configFile.store(out, "Template path");
				} finally {
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 刷新配置
	public static void refresh() throws IOException {
		configFile = new Properties();
		FileInputStream in = new FileInputStream(CONFIG_PATH);
		try {
			configFile.load(in);
		} finally {
			in.close();
		}
	}

	// 获得所有模板标识
	public static String[] getTemplateIds() {
		if (configFile != null) {
			String[] tems = new String[configFile.keySet().size()];
			return configFile.keySet().toArray(tems);
		}
		return null;
	}

	//
	public static String findPath(String identifier) {
		return configFile.getProperty(identifier);
	}

	// 获取模板路径
	public static URL findUrl(String identifier) {
		try {
			String path = configFile.getProperty(identifier);
			if (path != null) {
				File f = new File(path);
				if (f.exists())
					return f.toURL();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// 获得模板内容
	public static String loadTemplateContentByFile(String path)
			throws IOException, FileNotFoundException {
		StringBuffer content = new StringBuffer();
		File f = new File(path);
		FileInputStream input = new FileInputStream(f);
		byte[] b = new byte[500];
		int count = 0;
		while ((count = input.read(b)) > 0) {
			content.append(new String(b, 0, count));
			b = new byte[500];
		}
		input.close();
		return content.toString();
	}
}
